import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 创建axios实例
const service = axios.create({
    baseURL: "/api",
    timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token')
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`
        }
        return config
    },
    error => {
        console.error('请求错误：', error)
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        // 如果是二进制数据，直接返回
        if (response.config.responseType === 'blob') {
            return response;
        }

        const res = response.data;
        if (res.code === 200) {
            return res.data;
        }
        // Handle specific error codes
        if (res.code === 401) {
            localStorage.removeItem('token');
            router.push('/login');
            ElMessage.error('登录已过期，请重新登录');
        } else {
            ElMessage.error(res.message || '请求失败');
        }
        return Promise.reject(new Error(res.message || '请求失败'));
    },
    error => {
        ElMessage.error(error.message || '请求失败');
        return Promise.reject(error);
    }
)

export default service 